// timer-float.js
(function() {
  if (window.__taskTrackerFloatInjected) return;
  window.__taskTrackerFloatInjected = true;

  // 创建悬浮框DOM
  const floatBox = document.createElement('div');
  floatBox.id = 'task-timer-float-box';
  floatBox.style.fontFamily = "'Segoe UI', 'PingFang SC', Arial, sans-serif";
  floatBox.style.display = 'none'; // 初始隐藏
  floatBox.innerHTML = `
    <div class="float-header" style="padding:3px 8px 3px 10px;display:flex;align-items:center;justify-content:space-between;">
      <a id="float-logo-link" href="#" style="display:inline-flex;align-items:center;text-decoration:none;" title="Open Task Tracker">
        <svg width="14" height="14" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M24 4H6V17.3333V30.6667H24V44H42V30.6667V17.3333H24V4Z" fill="#222"></path></svg>
      </a>
      <button id="float-close-btn" style="background:none;border:none;font-size:15px;line-height:1;cursor:pointer;color:#aaa;padding:0 2px;">&times;</button>
    </div>
    <div class="float-body" id="float-task-list"></div>
  `;
  document.body.appendChild(floatBox);

  // 顶部logo点击跳转插件主页
  floatBox.querySelector('#float-logo-link').onclick = function(e) {
    e.preventDefault();
    window.open(chrome.runtime.getURL('home.html'), '_blank');
  };

  // 悬浮框关闭按钮
  floatBox.querySelector('#float-close-btn').onclick = function() {
    floatBox.style.display = 'none';
    sessionStorage.setItem('taskTimerFloatClosed', '1');
  };

  // 悬浮框拖拽功能
  let isDragging = false, dragOffsetX = 0, dragOffsetY = 0;
  const header = floatBox.querySelector('.float-header');
  header.style.cursor = 'move';
  header.onmousedown = function(e) {
    isDragging = true;
    dragOffsetX = e.clientX - floatBox.offsetLeft;
    dragOffsetY = e.clientY - floatBox.offsetTop;
    document.body.style.userSelect = 'none';
  };
  document.addEventListener('mousemove', function(e) {
    if (isDragging) {
      floatBox.style.left = (e.clientX - dragOffsetX) + 'px';
      floatBox.style.top = (e.clientY - dragOffsetY) + 'px';
      floatBox.style.right = 'auto';
      floatBox.style.bottom = 'auto';
    }
  });
  document.addEventListener('mouseup', function() {
    isDragging = false;
    document.body.style.userSelect = '';
  });

  // 计时格式化
  function formatTime(seconds) {
    const h = Math.floor(seconds / 3600).toString().padStart(2, '0');
    const m = Math.floor((seconds % 3600) / 60).toString().padStart(2, '0');
    const s = (seconds % 60).toString().padStart(2, '0');
    return `${h}:${m}:${s}`;
  }

  // 渲染悬浮框内容
  function renderFloatBox() {
    // 配置项控制
    if (localStorage.getItem('showFloatingTimer') === 'false') {
      floatBox.style.display = 'none';
      return;
    }
    // 用户主动关闭后，本会话不再弹出
    if (sessionStorage.getItem('taskTimerFloatClosed') === '1') {
      floatBox.style.display = 'none';
      return;
    }
    if (!(window.chrome && chrome.storage && chrome.storage.local)) {
      document.getElementById('float-task-list').innerHTML = '<div class="float-empty"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#aaa" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"></polyline></svg> Extension API unavailable</div>';
      floatBox.style.display = '';
      return;
    }
    chrome.storage.local.get(['taskTrackerTasks', 'taskTrackerTimerStates'], function(result) {
      let tasks = result.taskTrackerTasks || [];
      let timerStates = result.taskTrackerTimerStates || [];
      const runningIds = timerStates.map(t => t.taskId);
      const runningTasks = tasks.filter(t => runningIds.includes(t.id));
      const now = Date.now();
      if (!runningTasks.length) {
        floatBox.style.display = 'none';
        return;
      } else {
        floatBox.style.display = '';
      }
      const list = runningTasks.map(task => {
        const timer = timerStates.find(t => t.taskId === task.id);
        let elapsed = timer ? Math.floor((now - timer.startTime) / 1000) : (task.timeSpent || 0);
        return `<div class="float-task-item" title="${task.title}">
          <span class="float-task-title">${task.title}</span>
          <span class="float-task-time">${formatTime(elapsed)}</span>
        </div>`;
      });
      document.getElementById('float-task-list').innerHTML = list.join('');
    });
  }

  // 定时刷新
  setInterval(renderFloatBox, 1000);
  // 监听 chrome.storage 变化
  if (window.chrome && chrome.storage && chrome.storage.onChanged) {
    chrome.storage.onChanged.addListener(function(changes, area) {
      if (area === 'local' && (changes.taskTrackerTasks || changes.taskTrackerTimerStates)) {
        renderFloatBox();
      }
    });
  }
  renderFloatBox();

  // 每次刷新页面时清除关闭标记，确保刷新后可再次弹出
  sessionStorage.removeItem('taskTimerFloatClosed');
})(); 